<!-- @select="handleSelect" -->
<template>
    <div style="margin: 25px">
        <el-row>
            <el-col :xs="12" :sm="12" :lg="12">
                <el-input
                    class="inline-input"
                    v-model="searchProjectName"
                    prefix-icon="el-icon-search"
                    placeholder="搜索需要变更的项目名"
                    @input="searchProjectDebounce"
                    @clear="clearProject"
                    :autofocus="true"
                    clearable
                ></el-input>
            </el-col>
        </el-row>
        <el-row>
            <el-col :xs="24" :sm="24" :lg="12">
                <el-table
                    ref="singleTable"
                    :data="projects"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                    size="small"
                >
                    <el-table-column type="index" width="50"> </el-table-column>
                    <el-table-column property="name" label="项目名">
                    </el-table-column>
                    <el-table-column
                        property="project_start_date"
                        label="项目开始日期"
                        width="120"
                    >
                    </el-table-column>
                    <el-table-column
                        property="project_end_date"
                        label="项目结束日期"
                        width="120"
                    >
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row>
            <div style="margin-top: 20px">
                <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="medium"
                    round
                    @click="changeButton()"
                    :disabled="this.currentRow === null"
                    >变更</el-button
                >
            </div>
        </el-row>
        <el-row>
            <div class="log-container">
                <div style="height: auto">
                    <div :key="index" v-for="(row, index) in log">
                        <span class="line-number">{{ index + 1 }}</span>
                        <span class="line-content">{{ row }}</span>
                    </div>
                </div>
            </div>
        </el-row>
    </div>
</template>

<style>
.el-row {
    margin-bottom: 20px;
}
.el-table__body tr.current-row {
    background-color: #cfe1fc;
}
.log-container {
    box-sizing: border-box;
    color: rgb(173, 186, 199);
    font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
    font-size: 12px;
    line-height: 18px;
    margin-bottom: 8px;
    margin-left: 8px;
    margin-right: 8px;
    margin-top: 8px;
    overflow-wrap: break-word;
    padding-bottom: 4px;
    padding-top: 4px;
    scrollbar-color: rgb(68, 76, 86) rgb(30, 34, 40);
}
.line-number {
    width: 48px;
    overflow: hidden;
    color: #768390;
    text-align: right;
    text-decoration: none;
    text-overflow: ellipsis;
    white-space: nowrap;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.line-content {
    overflow-x: auto;
    white-space: pre-wrap;
    color: #768390;
}
</style>

<script>
import _ from 'lodash';
import { getName } from '@/utils/auth';

import {
    getProjectPeriods,
    initHistoryLabourInput,
    sumHistoryTotalManMonth,
    sumTotalManMonthList,
    getBusinessType,
    getProductionCategory,
} from '@/views/project_request/data';

import {
    getSubProjectId,
    getDepartmentId,
    getDepartmentById,
} from '@/views/project_request/fetch';

export default {
    data() {
        return {
            log: [],
            projectName: '',
            searchProjectName: '',
            projectId: '',
            inputDebounce: 300,
            userId: '',
            submitter:'',
            isProjectManager: false,
            form: {},
            calculated: {},
            projects: [],
            currentRow: null,
            queryString: '',
            loading: false,
            ldap:getName()
        };
    },
    mounted() {
        this.getUserInfo();
    },
    created() {
        this.searchProjectDebounce = _.debounce(this.searchProject, 400);
    },
    methods: {
        clearProject() {
            this.projects = [];
        },
        appendLog(msg) {
            this.log.push(msg);
        },
        getDuration(endDate, startDate) {
            let end = new Date(endDate).getTime();
            let start = new Date(startDate).getTime();
            let duration = (end - start) / (24 * 60 * 60 * 30 * 1000);
            return Math.floor(duration * 10) / 10;
        },
        searchProject(queryString) {
            const url = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/project/query`;
            if (queryString != undefined && queryString.length > 2) {
                this.$axios
                    .get(url, { params: { name: queryString } })
                    .then((response) => {
                        this.projects = response.data.data;
                    });
            }
        },
        handleCurrentChange(val) {
            this.currentRow = val;
            this.projectName = val.name;
        },
        changeButton() {
            let row = this.currentRow;
            if (row) {
                if (row.project_manager.toString() === this.userId.toString()) {
                    this.changeProject(row.id);
                } else {
                    this.$message.error('非项目经理');
                }
            }
        },
        formSave(data) {
            return new Promise((resolve, reject) => {
                this.$axios({
                    url: `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/project/apply`,
                    method: 'post',
                    data: data,
                })
                    .then((response) => {
                        resolve(response);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                this.$axios
                    .get(
                        `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/employee/`,
                        {
                            params: {
                                ldap: getName(),
                            },
                        }
                    )
                    .then((response) => {
                        this.userId = response.data.data[0].id;
                        this.submitter = response.data.data[0].name;
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        fetchFromStandingBook(projectName) {
            return new Promise((resolve, reject) => {
                const url = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/oracle_view`;
                this.$axios
                    .get(url, { params: { project_name: projectName } })
                    .then((res) => {
                        if (res.data === {}) {
                            resolve(404);
                        }
                        // 台账中为"None"的值替换成""
                        const data = _.mapValues(res.data, (value, key) => {
                            if (value === 'None') {
                                return '';
                            }
                            return value;
                        });
                        // 计算周期
                        let start = new Date(data.xmksrq);
                        let end = new Date(data.xmjsrq);
                        const duration = end.getTime() - start.getTime();
                        const months = duration / (24 * 60 * 60 * 30 * 1000);
                        let projectPeriod = Math.floor(months * 10) / 10;
                        
                        // 构建表单数据
                        let formData = {
                            form:{
                                process_compliance: data.lcfhd,
                                created_at: data.lxrq,
                                project_summary: data.xmgy,
                                defect_density: data.qgcqxmd,
                                software_platform: data.rjpt,
                                software_version: data.rjptbb,
                                project_level: data.xmjb,
                                project_manager_id: data.xmjl,
                                sales_id: data.xsry,
                                entire_subcontract: data.sfztzb1 === 3,
                                is_pre_dev: data.sfyyxm === 0,
                                income_check_method: data.srqrfsxml,
                                security_level: data.xxaqjb,
                                one_time_release_success_rate: data.rjycffbcgl,
                                hardware_version: data.yjptbb,
                                hardware_platform: data.yjptnew,
                                est_market_size_over_20_million: data.yjscgm,
                                currency_id: parseInt(data.bz1),
                                currency: parseFloat(data.zshl).toFixed(6),
                                business_department_id: data.lxsyb,
                                // FIXME 台账缺少业务类型细分
                                business_type: [
                                    data.ywlx.toString(),
                                    data.ywlxxf.toString()
                                ],
                                product_category: [
                                    data.cplx.toString(),
                                    data.cplxxf.toString(),
                                ],
                                // 项目开始，结束，周期
                                init_project_start_date: data.xmksrq,
                                init_project_end_date: data.xmjsrq,
                                project_start_date: data.xmksrq,
                                project_end_date: data.xmjsrq,
                                project_period: projectPeriod,
                                projectPeriod: projectPeriod,
                                // OA新增的字段
                                workhour_status: data.gszt || '',
                                billing_period: data.zq,
                                hardware_revision_count: data.yjgbcsnew,
                                corporation_id: data.cdgsqs,
                                deal_id: data.dd,
                                sales:data.xsryxm,
                                customer_full_name:data.khqc,
                                customer_region : data.khdz,
                                corporation : data.gsqc,
                                product: data.zjscpzxm,
                                canEditProjectDirector:false,
                            },
                            calculated:{
                                avg_cost_RMB: parseFloat(data.rjcbrmb1 || 0),
                                avg_income_RMB: parseFloat(data.rjsrrmb1 || 0),
                                est_cost: parseFloat(data.yjztrrmb1 || 0),
                                est_income: parseFloat(data.yjzsrrmb1 || 0),
                                est_income_raw: parseFloat(data.yjzsryb1 || 0),
                                ldap: this.ldap,
                                profit:parseFloat(data.yjmlrmb1 || 0),
                                profit_rate: parseFloat(data.yjmll1 || 0),
                                submitter:this.submitter,
                                total_man_month: parseFloat(data.yjztrry1 || 0),
                            }
                        };
                        resolve(formData);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        requestChangeProject(projectId) {
            return new Promise((resolve, reject) => {
                const url = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/workflow/change`;
                this.$axios
                    .post(url, { project_id: projectId })
                    .then((res) => {
                        this.loadFormData(res.data.data.form_id , this.projectName);
                        this.loading = false;
                        resolve(res.data);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        changeProject(projectId) {
            this.loading = true;
            this.appendLog('准备变更项目');
            this.requestChangeProject(projectId).then((data) => {
                if (data.code === 200) {
                    this.appendLog(`${data.msg}，跳转中`);
                    setTimeout(
                        () =>
                            this.$router.push({
                                name: 'edit',
                                params: { id: data.data.form_id },
                            }),
                        1500
                    );
                    return;
                }else if(data.code === 400){
                    this.appendLog(`${data.msg},无法跳转`);
                    return;
                }
                // 拉取台账数据
                this.fetchFromStandingBook(this.projectName)
                    .then((data) => {
                        // 重新拉取立项事业部信息;
                        this.appendLog('从台账拉取立项事业部信息');
                        return new Promise((resolve, reject) => {
                            resolve(data);
                        });
                    })
                    .then((data) => {
                        getDepartmentById(data.form.business_department_id).then(
                            (departmentData) => {
                                const oldForm = this.form;
                                const calculated = this.calculated;
                                const oldCalculated = data.calculated;
                                let formData = Object.assign(
                                    {},
                                    this.form,
                                    data.form,
                                    departmentData
                                );
                                formData.init_project_end_date = data.form.init_project_end_date || '';
                                formData.init_project_start_date = data.form.init_project_start_date || '';
                                if (
                                    formData.business_department_id !==
                                    data.business_department_id
                                ) {
                                    this.appendLog(
                                        `立项事业部更新: ${this.form.business_department} => ${departmentData.business_department}`
                                    );
                                    if (
                                        Array.isArray(
                                            formData.incomeDistribution
                                        ) &&
                                        formData.incomeDistribution.length
                                    ) {
                                        this.appendLog(`收入拆分BU部门更新`);
                                        formData.incomeDistribution[0].manager_id =
                                            formData.project_manager_id;
                                        formData.incomeDistribution[0].manager =
                                            formData.project_manager;
                                        formData.incomeDistribution[0].implement_department_id =
                                            departmentData.business_department_id;
                                        formData.incomeDistribution[0].implement_department =
                                            departmentData.business_department;
                                        formData.incomeDistribution[0].sub_project_name =
                                            departmentData.project_name;
                                        formData.incomeDistribution.forEach((item,index)=>{
                                            if(index > 0){
                                                this.$axios.get(
                                                    `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/oracle_view?project_name=${item.sub_project_name}`
                                                ).then(res=>{
                                                    formData.incomeDistribution[index].implement_department = 
                                                        res.data.ssbmmc;
                                                    formData.incomeDistribution[index].manager_id = 
                                                        res.data.xmglry;
                                                    formData.incomeDistribution[index].manager = 
                                                        res.data.xmglryxm;
                                                }).catch(err=>{
                                                    console.log(err)
                                                })
                                            }
                                        })
                                    }
                                }
                                
                                // TODO 拉取其它Id字段相关信息
                                let submitData = {
                                    form: formData,
                                    form_old: oldForm,
                                    calculated: calculated,
                                    calculated_old: oldCalculated,
                                };
                                this.appendLog('保存项目信息');
                                this.formSave(submitData).then((res) => {
                                    this.appendLog('跳转至编辑页面');
                                    setTimeout(
                                        () =>
                                            this.$router.push({
                                                name: 'edit',
                                                params: {
                                                    id: res.data.data.form_id,
                                                },
                                            }),
                                        1500
                                    );
                                });
                            }
                        );
                    });
            });
            this.form.project_id = projectId;
        },
        loadFormData(formId , projectName) {
            const url = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/project/apply`;
            this.$axios({
                url: url,
                method: 'get',
                params: { id: formId , project_name: projectName },
            }).then((res) => {
                if (res.data.code === 200) {
                    this.version = res.data.version;
                    this.requestType = res.data.request_type;
                    for (const d in res.data.data.form) {
                        this.form[d] = res.data.data.form[d];
                    }
                    if (
                        res.data.data.form.project_start_date &&
                        res.data.data.form.project_end_date
                    ) {
                        // 计算项目周期
                        let { pastMonths, nextMonths } = getProjectPeriods(
                            res.data.data.form.project_start_date,
                            res.data.data.form.project_end_date,
                            this.requestType === 1
                        );
                        if (this.requestType === 1 && this.mode !== 'view') {
                            let start = new Date(
                                res.data.data.form.project_start_date
                            );
                            let end = new Date(
                                res.data.data.form.project_end_date
                            );
                            const duration = end.getTime() - start.getTime();
                            const monthDuration =
                                duration / (24 * 60 * 60 * 30 * 1000);
                            let projectPeriod =
                                Math.floor(monthDuration * 10) / 10;
                            this.form.created_at =
                                res.data.data.form.created_at;
                            this.form.oldProjectPeriod = this.getDuration(
                                this.form.init_project_end_date,
                                this.form.init_project_start_date
                            );
                            this.projectPeriod = projectPeriod;
                            this.form.project_period = projectPeriod;
                            this.form.pastMonths = pastMonths;
                            this.form.nextMonths = nextMonths;
                            this.form.allMonths = pastMonths.concat(nextMonths);
                        } else if (
                            this.requestType === 1 &&
                            this.mode === 'view'
                        ) {
                            console.log('load months');
                        } else {
                            this.form.pastMonths = [];
                            this.form.nextMonths = nextMonths;
                            this.form.allMonths = nextMonths;
                        }
                        // 初始化历史人力
                        this.form.historyManPowerInput = initHistoryLabourInput(
                            Math.ceil(pastMonths.length)
                        );
                        // 分配公司人力历史
                        this.form.historyManPowerInput[0].input = sumTotalManMonthList(
                            res.data.data.form.manPowerInput
                        ).slice(0, pastMonths.length);
                        // 清空立项资料
                        this.form.file_list = [];
                        // 清空特批事项
                        this.form.special_approval_list = [];
                        this.form.special_approval = '';
                        this.form.historyManPowerInput.forEach(
                            (item, index) => {
                                if (
                                    item.input.length <
                                    this.form.pastMonths.length
                                ) {
                                    let arr = new Array(
                                        this.form.pastMonths.length -
                                            item.input.length
                                    ).fill(0);
                                    this.form.historyManPowerInput[
                                        index
                                    ].input = this.form.historyManPowerInput[
                                        index
                                    ].input.concat(arr);
                                }
                            }
                        );
                        // 载入公司人力
                        res.data.data.form.manPowerInput.forEach(
                            (item, index) => {
                                if (item.input.length === 0) {
                                    this.form.manPowerInput[
                                        index
                                    ].input = new Array(
                                        this.form.allMonths.length
                                    ).fill(0);
                                }
                                if (
                                    this.requestType === 1 
                                ) {
                                    // 分配公司人力预测
                                    this.form.manPowerInput[
                                        index
                                    ].input = item.input.slice(
                                        pastMonths.length
                                    );
                                }
                            }
                        );
                        // 载入外包人力
                        res.data.data.form.manPowerOutSourcingInput.forEach(
                            (item, index) => {
                                if (item.input.length === 0) {
                                    this.form.manPowerOutSourcingInput[
                                        index
                                    ].input = new Array(
                                        this.form.allMonths.length
                                    ).fill(0);
                                }
                                if (
                                    this.requestType === 1 
                                ) {
                                    // 分配外包人力预测
                                    this.form.manPowerOutSourcingInput[
                                        index
                                    ].input = item.input;
                                };
                            }
                        );
                        // 载入拆分部门Id
                        res.data.data.form.incomeDistribution.forEach(
                            (item, index) => {
                                if (
                                    !item.hasOwnProperty(
                                        'implement_department_id' &&
                                            item.hasOwnProperty(
                                                'implement_department'
                                            )
                                    )
                                ) {
                                    getDepartmentId(
                                        item.implement_department
                                    ).then((data) => {
                                        this.form.incomeDistribution[
                                            index
                                        ].implement_department_id = data.id;
                                    });
                                }
                            }
                        );
                        // 载入子项目Id
                        res.data.data.form.incomeDistribution.forEach(
                            (item, index) => {
                                if (this.mode === 'change') {
                                    if (
                                        item.hasOwnProperty('sub_project_name')
                                    ) {
                                        this.form.enableSubProjectName = true;
                                    } else {
                                        this.form.enableSubProjectName = false;
                                    }
                                }
                                getSubProjectId(item.sub_project_name).then(
                                    (data) => {
                                        this.form.incomeDistribution[
                                            index
                                        ].sub_project_id = data.id;
                                    }
                                );
                            }
                        );
                    }
                    this.oldForm = res.data.data.form_old;
                    this.calculated = res.data.data.calculated;
                    this.estCost = res.data.data.calculated.est_cost;
                    this.estIncome = res.data.data.calculated.est_income;
                    this.estIncomeRaw = res.data.data.calculated.est_income_raw;
                    this.profit = res.data.data.calculated.profit;
                    this.profit_rate = res.data.data.calculated.profit_rate;
                    this.totalManMonth =
                        res.data.data.calculated.total_man_month;
                    this.avgCostRMB = res.data.data.calculated.avg_cost_RMB;
                    let readValue = this.form.project_level;
                    this.form.project_level = String(readValue);
                    let readValue2 = this.form.security_level;
                    this.form.security_level = String(readValue2);
                    let readValue3 = this.form.est_market_size_over_20_million;
                    this.form.est_market_size_over_20_million = String(
                        readValue3
                    );
                } else {
                    this.errMessage = '无效的请求';
                }
            });
        },
    },
};
</script>
